from flask import Flask
from flask import request
from bs4 import BeautifulSoup
import xml.etree.cElementTree as ET
import jieba
import jieba.posseg as pseg
app = Flask(__name__)
@app.route('/')
def hello_world():
    return 'Hello World!'
# 微信接受api位置
@app.route("/WeChat/WeChatServlet", methods=['POST'])
def WeChatServlet():
    # print("请求方法：", request.method)
    # args =request.args.get("signature")
    # print("signature:", args)
    # args =request.args.get("timestamp")
    # print("timestamp:", args)
    # args =request.args.get("nonce")
    # print("nonce:", args)
    # args =request.args.get("openid")
    # print("openid:", args)
    soup = BeautifulSoup(request.data, "html.parser")
    # print(soup)
    root = ET.fromstring(str(soup))
    # 获取到客户端说的话
    mes =root[4].text
    print("客户端说：", mes)
    """
    参数	描述
    ToUserName	发送人客户端
    FromUserName	发送方帐号（一个OpenID）服务端
    CreateTime	消息创建时间 （整型）
    MsgType	text
    Content	文本消息内容 3b7160c1591868f755dc8fb6fbcf9f8b
    MsgId	消息id，64位整型AppID wxdcc685b845fe89ae
    """
    types = root[3].text
    tousername = 'gh_0ab15cc0c225'
    fromusername = root[1].text
    msgtype = 'text'
    content = '你发送的类型是：%s'%types
    msgid = '1234567890123456'
    # 获取消息类型
    # for i in root:
    #     print(i.text)
    # 定义关键字
    words =['我想', '我要', '帮我', '你能', '有没有', '查', '查找', '什么意思', '翻译', '每日', '给我']

    seg_list = jieba.cut(mes, cut_all=False)
    result ="\n\nDefault Mode: " + "/ ".join(seg_list)
    print(result)  # 精确模式
    # 得到主谓的结构词语

    seg_list = list(pseg.cut(mes))  # 默认是精确模式
    # result = seg_list
    print(seg_list)
    # for word, flag in seg_list:
    #     print("%s  %s" % (word, flag))
    # 得到带简称的主谓结构词语
    # jieba分词 主谓宾
    """
    r 代表主词
    v 代表动词
    
    
    """
    mes += "\n\n" + result + "\n\n" + str(seg_list)
    for word in words:
        if word in mes:

            print("存在啊")
            break


    if msgtype =="text":

        text1 = '\n文字处理中...\n\n'+mes
        pass
    elif msgtype =="video":
        text1 = '\n视频处理中...'+mes
        pass
    elif msgtype =="voice":
        text1 = '\n声音处理中...'+mes

        pass
    elif msgtype =="location":
        text1 = '\n位置处理中...'+mes
        pass
    result = """<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>1535096785981</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s%s]]></Content></xml>""" % (
    fromusername, tousername, content, text1)
    return result

def read_xml(in_path):
    """读取并解析xml文件
       in_path: xml路径
       return: tree"""
    tree = ET.parse(in_path)
    for i in tree:
        print(i)
if __name__ == '__main__':
    app.run(
        host = '0.0.0.0',
        port = 7777,
        debug = True
    )
